/**
 * The contents of this file are subject to the OpenMRS Public License
 * Version 1.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://license.openmrs.org
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * Copyright (C) OpenMRS, LLC.  All Rights Reserved.
 */
package org.openmrs.module.datalogging.handler.variable;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.BaseOpenmrsObject;
import org.openmrs.Encounter;
import org.openmrs.Person;
import org.openmrs.api.context.Context;
import org.openmrs.module.datalogging.configuration.Variable;
import org.openmrs.module.datalogging.enums.OffsetType;
import org.openmrs.module.datalogging.filter.FilterUtils;
import org.openmrs.module.datalogging.service.DataLoggingService;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 *
 */
public class EncounterVariableHandler extends OpenmrsVariableHandler {
	
	private static final Log log = LogFactory.getLog(EncounterVariableHandler.class);
	
	/**
	 * @see org.openmrs.module.datalogging.handler.variable.VariableHandler#handle(Person,
	 *      org.openmrs.module.datalogging.configuration.Variable, Object)
	 */
	@Override
	public Object handle(Person person, Variable variable, Object object) {
		
		Object returnValue = null;
		
		// format for encounter filter expression is:
		// - type=x,y,z;location=a,b,c
		DataLoggingService service = Context.getService(DataLoggingService.class);
		// need to perform the encounter search here
		try {
			Map<String, Set<BaseOpenmrsObject>> map = FilterUtils.parseFilter(variable);
			List<Encounter> encounters = service.findEncounters(person, map);
			if (!encounters.isEmpty()) {
				Encounter encounter = null;
				
				int minSize = variable.getValueOffset();
				if (minSize < 0)
					minSize = minSize - 1;
				
				// make sure we have enough observations in the list to accommodate the offset value
				if (encounters.size() > Math.abs(minSize)) {
					
					if (variable.getOffsetType() == OffsetType.FIRST_ELEMENT)
						encounter = encounters.get(variable.getValueOffset());
					else if (variable.getOffsetType() == OffsetType.LATEST_ELEMENT)
						encounter = encounters.get((encounters.size() - 1) + variable.getValueOffset());
					
					returnValue = PropertyUtils.getProperty(encounter, variable.getValueExpression());
				}
			}
		} catch (Exception e) {
			log.error("Error reading bean property ...", e);
		}
		
		return returnValue;
	}
	
	@Override
	protected void registerFilters() {
		registerFilter("encounterType");
		registerFilter("location");
	}
}
